package com.mdlib.helper.ui.fragments.sect.run;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ljlib.core.util.BitmapUtil;
import com.ljlib.core.util.EmptyUtils;
import com.ljlib.core.util.PicPath;
import com.ljlib.core.util.common.RegularUtils;
import com.ljlib.core.util.common.StringUtils;
import com.ljlib.help.R;
import com.mdlib.helper.api.DataManager;
import com.mdlib.helper.api.MDUploadPic;
import com.mdlib.helper.api.network.RxHelper;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.base.BaseTitleFragment;
import com.mdlib.helper.event.ImageID;
import com.mdlib.helper.event.SelectEvent;
import com.mdlib.helper.model.BaseResult;
import com.mdlib.helper.model.UserModel;
import com.mdlib.helper.model.entity.AgreementEntity;
import com.mdlib.helper.model.entity.SelectEntity;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.utils.ToastUtil;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 作者：HQY on 16/11/25 14:24
 * 邮箱：hqy_xz@126.com
 */

public class ApplyRunManFragment extends BaseTitleFragment implements EasyPermissions.PermissionCallbacks {
    private static final int CAPTURE_IMAGE_CAMERA = 100;
    private static final int IMAGE_STORE = 200;
    private static final int CAMERA_PERM = 1;
    private static final String PIC = "pic";


    private static final String BIGHEAD = "bighead";
    private static final String HAND = "hand";
    private static final String FRONT = "front";
    private static final String REVERSE = "reverse";


    @Bind(R.id.et_apply_name)
    EditText mEtApplyName;
    @Bind(R.id.et_apply_id_number)
    EditText mEtApplyIdNumber;
    @Bind(R.id.et_apply_urgent_phone)
    EditText mEtApplyUrgentPhone;
    @Bind(R.id.et_apply_bind_phone)
    TextView mEtApplyBindPhone;
    @Bind(R.id.iv_apply_headshot)
    ImageView mIvApplyHeadshot;
    @Bind(R.id.iv_apply_positive)
    ImageView mIvApplyPositive;
    @Bind(R.id.iv_apply_id_positive)
    ImageView mIvApplyIdPositive;
    @Bind(R.id.iv_apply_id_negative)
    ImageView mIvApplyIdNegative;
    @Bind(R.id.cb_apply_run_man)
    CheckBox mCbApplyRunMan;
    @Bind(R.id.tv_apply_run_man_protocol)
    TextView mTvApplyRunManProtocol;
    @Bind(R.id.tv_apply_run_man_submint)
    TextView mTvApplyRunManSubmint;
    private Dialog mRunManDialog;

    private String[] str = {"相册", "拍照"};
    private List<SelectEntity> selectList = new ArrayList<>();
    private Uri origUri;
    private String type = BIGHEAD;
    private String head_pic;
    private String take_card;
    private String face_card;
    private String back_card;

    private String mAgreementUrl;//跑客注册协议链接


    public static ApplyRunManFragment newInstance() {
        return new ApplyRunManFragment();
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_apply_run_man;
    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        EventBus.getDefault().register(this);
        setTitle(R.string.apply_run_man_title, R.color.white)
                .setTitleBgColor(R.color.generic_view_bg)
                .setImgLeftListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        removeFragment();
                    }
                });
        init();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private void init() {
        mEtApplyBindPhone.setText(UserModel.getInstance().getPhone());
        getRunAgreement();
        getPicList();
    }

    private void getPicList() {
        for (int i = 0; i < str.length; i++) {
            SelectEntity select = new SelectEntity();
            select.setId(i);
            select.setTitle(str[i]);
            selectList.add(select);
        }
    }

    @OnClick({R.id.iv_apply_headshot, R.id.iv_apply_positive, R.id.iv_apply_id_positive, R.id.iv_apply_id_negative, R.id.tv_apply_run_man_protocol, R.id.tv_apply_run_man_submint})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_apply_headshot:
                type = BIGHEAD;
                UIHelper.showSelectList(getActivity(), selectList, PIC);
                break;
            case R.id.iv_apply_positive:
                type = HAND;
                UIHelper.showSelectList(getActivity(), selectList, PIC);
                break;
            case R.id.iv_apply_id_positive:
                type = FRONT;
                UIHelper.showSelectList(getActivity(), selectList, PIC);
                break;
            case R.id.iv_apply_id_negative:
                type = REVERSE;
                UIHelper.showSelectList(getActivity(), selectList, PIC);
                break;
            case R.id.tv_apply_run_man_protocol:
                UIHelper.showWebPage(getActivity(), "用户协议", mAgreementUrl);
                break;
            case R.id.tv_apply_run_man_submint:
                String name = mEtApplyName.getText().toString();
                String id = mEtApplyIdNumber.getText().toString();
                String urgentPhone = mEtApplyUrgentPhone.getText().toString();
                String phone = mEtApplyBindPhone.getText().toString();

                if (EmptyUtils.isEmpty(name)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.apply_run_man_ral_name_tips));
                    return;
                }
                if (EmptyUtils.isEmpty(id)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.apply_run_man_id_number_tips));
                    return;
                }
                if (EmptyUtils.isEmpty(urgentPhone)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.apply_run_man_urgent_phone_tips));
                    return;
                }
                if (!RegularUtils.isMobileExact(urgentPhone)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.generic_et_phone_form));
                    return;
                }
                if (EmptyUtils.isEmpty(phone)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.apply_run_man_bind_phone_tips));
                    return;
                }
                if (EmptyUtils.isEmpty(head_pic)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.apply_run_man_headshot_tips));
                    return;
                }
                if (EmptyUtils.isEmpty(take_card)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.apply_run_man_positive_negative_tips));
                    return;
                }
                if (EmptyUtils.isEmpty(face_card)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.apply_run_man_positive_tips));
                    return;
                }
                if (EmptyUtils.isEmpty(back_card)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.apply_run_man_negative_tips));
                    return;
                }
                if (!mCbApplyRunMan.isChecked()) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.apply_run_man_protocol_tips));
                    return;
                }
                applyRun(name, urgentPhone, phone, id);

                break;
        }

    }

    private void getRunAgreement() {
        addSubscribe(DataManager.getInstance().getAccountApi().featchRunAgreement()
                .compose(RxHelper.<AgreementEntity>defaultHandleResult())
                .subscribe(new RxSubscribe<AgreementEntity>() {
                    @Override
                    protected void onSucc(AgreementEntity agreementEntity) {
                        mAgreementUrl = agreementEntity.getUrl();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    /**
     * 申请跑客
     *
     * @param name
     * @param urgentPhone
     * @param phone
     * @param id
     */
    private void applyRun(String name, String urgentPhone, String phone, String id) {
        startLoadingDialog(true);
        addSubscribe(DataManager.getInstance().getUserApi()
                .applyRun(name, id, urgentPhone, phone, head_pic, take_card, face_card, back_card)
                .compose(RxHelper.<BaseResult>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult>() {
                    @Override
                    protected void onSucc(BaseResult baseResult) {
                        stopLoadingDialog();
                        mRunManDialog = new Dialog(getActivity(), R.style.dialog);
                        mRunManDialog.setContentView(R.layout.dialog_apply_run_man_success);

                        TextView outTv = (TextView) mRunManDialog.findViewById(R.id.tv_dialog_ok);
                        outTv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mRunManDialog.dismiss();
                                getActivity().finish();
                            }
                        });
                        mRunManDialog.show();
                    }

                    @Override
                    protected void onFail(String msg) {
                        stopLoadingDialog();
                        ToastUtil.showToast(msg);

                    }
                }));

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SelectEvent selectEvent) {
        if (selectEvent.getSelectEntity().getTitle().equals(str[0])) {
            startImagePick();
        } else if (selectEvent.getSelectEntity().getTitle().equals(str[1])) {
            startTakePhotoByPermissions();
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        BitmapUtil bitmapUtil = new BitmapUtil();
        switch (requestCode) {
            case CAPTURE_IMAGE_CAMERA:
                String urlImage = bitmapUtil.prepareFile(origUri.getPath());
                Logger.e("拍照之后图片路径: " + urlImage);
                getImageId(urlImage);
                break;
            case IMAGE_STORE:
                String path = PicPath.getPath(getActivity(), data.getData());
                String urlImages = bitmapUtil.prepareFile(path);
                Logger.e("选图之后图片路径: " + urlImages);
                getImageId(urlImages);
                break;


        }
    }


    private void getImageId(String name) {
        List<String> nameList = new ArrayList<>();
        nameList.add(name);
        MDUploadPic.uploadPic(nameList, getActivity(), "1");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ImageID id) {
        if (id.getIdList().size() < 0) {
            return;
        }
        if (type.equals(BIGHEAD)) {
            head_pic = id.getIdList().get(0);
            Glide.with(getActivity()).load(new File(id.getUrlList().get(0))).into(mIvApplyHeadshot);
        } else if (type.equals(HAND)) {
            take_card = id.getIdList().get(0);
            Glide.with(getActivity()).load(new File(id.getUrlList().get(0))).into(mIvApplyPositive);
        } else if (type.equals(FRONT)) {
            face_card = id.getIdList().get(0);
            Glide.with(getActivity()).load(new File(id.getUrlList().get(0))).into(mIvApplyIdPositive);
        } else if (type.equals(REVERSE)) {
            back_card = id.getIdList().get(0);
            Glide.with(getActivity()).load(new File(id.getUrlList().get(0))).into(mIvApplyIdNegative);

        }

    }

    /**
     * 选择图片
     */

    private void startImagePick() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            getActivity().startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    IMAGE_STORE);
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            getActivity().startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    IMAGE_STORE);
        }
    }

    @AfterPermissionGranted(CAMERA_PERM)
    private void startTakePhotoByPermissions() {
        String[] perms = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this.getContext(), perms)) {
            try {
                startTakePhoto();
            } catch (Exception e) {
                Toast.makeText(this.getContext(), R.string.permissions_camera_error, Toast.LENGTH_LONG).show();
            }
        } else {
            // Request one permission
            EasyPermissions.requestPermissions(this,
                    getResources().getString(R.string.str_request_camera_message),
                    CAMERA_PERM, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        try {
            startTakePhoto();
        } catch (Exception e) {
            Toast.makeText(this.getContext(), R.string.permissions_camera_error, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Toast.makeText(this.getContext(), R.string.permissions_camera_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    private void startTakePhoto() {
        Intent intent;
        // 判断是否挂载了SD卡
        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/helper/Camera/";
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }

        // 没有挂载SD卡，无法保存文件
        if (StringUtils.isEmpty(savePath)) {
            ToastUtil.showToast("无法保存照片，请检查SD卡是否挂载");
            return;
        }

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        String fileName = "zb_" + timeStamp + ".jpg";// 照片命名
        File out = new File(savePath, fileName);
        Uri uri = Uri.fromFile(out);
        origUri = uri;

        String theLarge = savePath + fileName;

        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        getActivity().startActivityForResult(intent,
                CAPTURE_IMAGE_CAMERA);
    }

}
